package com.fingard.dsp.bank.directbank.bjrc11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;

public class BJRC11BatPayRec extends BJRC11Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        retAts.reqSeqID = p_reqBat.reqBatchNO;

        try {
            StringBuilder sbFileContent = new StringBuilder();
            while (p_reqBat.readRecord()) {
                if (sbFileContent.length() > 0) {
                    sbFileContent.append("\n");
                }
                String oppAct = "";
                String oppName = "";
                if ("1988".equals(p_reqBat.reqHeader.transType)) {
                    oppAct = p_reqBat.readedDetail.recAct;
                    oppName = p_reqBat.readedDetail.recName;
                } else {
                    oppAct = p_reqBat.readedDetail.payAct;
                    oppName = p_reqBat.readedDetail.payName;
                }
                String policyNo = p_reqBat.readedDetail.sourceNoteCode;
                String payAmt = p_reqBat.readedDetail.payAmount;
                String memo = p_reqBat.reqBatchNO + "-" + p_reqBat.readedDetail.askNumber;

                //批次号（4位）|银行账号（30位）|金额（16位）|保单号（20位）|客户名称（60位）|备注(100位)|
                String tmpReqBodyDetail = MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}|", "0001", oppAct, payAmt, policyNo, oppName, memo);
                sbFileContent.append(tmpReqBodyDetail);
            }
            WriteBankLogLn2("批量代收付请求文件内容:\r\n" + sbFileContent.toString());

            String cdFlag = "PF";
            if (p_reqBat.reqHeader.isBatRec) {
                cdFlag = "PK";
            }
            String tmpPaySendDate = Format.Date8Format.format(p_reqBat.getPayDateTime());
            String tmpUploadFileName = "BRCB_" + cdFlag + "_L_" + tmpPaySendDate + ".txt";
            String tmpLocalMarkPath = getTempFileDirectory() + File.separator + tmpUploadFileName;
            WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalMarkPath);

            boolean isSummaryUpload = getBankConfig().getValueAsBool("isSummaryUpload");
            if (isSummaryUpload) {
                FileHelper.appendFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());
                retAts.respCode = "0";
                retAts.respInfo = "上传成功";
                retAts.transState = "Uploaded";
                retAts.payInfoCode = "I4001";
            } else {
                if (FileHelper.existFile(tmpLocalMarkPath)) {
                    retAts.respCode = "0";
                    retAts.respInfo = "本地批次文件已上传,请勿重复上传!";
                    retAts.reqSeqID = p_reqBat.reqBatchNO;
                    retAts.transState = PaymentState.FAIL_Batch;
                    retAts.payInfoCode = FailCode.E9981;
                    retAts.writeRetToATS();
                    return retAts;
                }
                String totalContent = tmpPaySendDate + "|" + p_reqBat.totalNum + "|" + p_reqBat.totalAmt + "|\n";
                FileHelper.appendFile(tmpLocalMarkPath, totalContent + sbFileContent.toString(), getCharset());

                FtpSet ftpSet = bankFront.getFtpSet("bat");
                String ftpUpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + tmpUploadFileName;
                WriteBankLogLn("当日批次文件上传FTP服务器路径:" + ftpUpFilePath);
                FtpReceiver ftpReceiver = null;
                String requestType = getBankConfig().getValueAsString("requestType");
                if (requestType != null && "SFTP".equals(requestType)) {
                    SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                    String sftpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + tmpUploadFileName;
                    ftpReceiver = sftpPortClient.uploadFile("", tmpLocalMarkPath, sftpFilePath);
                    sftpPortClient.disconnect();
                } else {
                    FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                    ftpReceiver = ftpPortClient.uploadFile(tmpLocalMarkPath, tmpUploadFileName);
                    ftpPortClient.disconnect();
                }

                retAts.respCode = "0";
                if (!ftpReceiver.isCompleted) {
                    retAts.respCode = "-1";
                    retAts.respInfo = ftpReceiver.connMsg;
                } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                    retAts.respInfo = "上传失败";
                    retAts.transState = "BatchFailed";
                    retAts.payInfoCode = "E9999";
                } else {
                    retAts.respInfo = "上传成功";
                    retAts.transState = "Uploaded";
                    retAts.payInfoCode = "I4001";
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetToATS();
        return retAts;
    }

    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;

        try {
            String tmpPaySendDate = Format.Date8Format.format(p_reqQryBat.getBgnDateTime());
            String cdFlag = "PF";
            if ("9198".equalsIgnoreCase(p_reqQryBat.reqHeader.transType)) {
                cdFlag = "PK";
            }
            String tmpDownFileName = "BRCB_" + cdFlag + "_H_" + tmpPaySendDate + ".txt";
            String tmpLocalMarkPath = createTempFileDirectory() + File.separator + tmpDownFileName;
            WriteBankLogLn2("批次结果文件保存本地路径: " + tmpLocalMarkPath);

            FtpSet ftpSet = bankFront.getFtpSet("bat");
            FtpReceiver ftpReceiver = null;
            String requestType = getBankConfig().getValueAsString("requestType");
            if (requestType != null && "SFTP".equals(requestType)) {
                String sftpFilePath = StringHelper.trimEnd(ftpSet.downDir, "/") + "/" + tmpDownFileName;
                WriteBankLogLn2("待下载SFTP服务器文件路径:\r\n" + sftpFilePath);
                SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                ftpReceiver = sftpPortClient.downloadFile("", sftpFilePath, tmpLocalMarkPath);
                sftpPortClient.disconnect();
            } else {
                FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                ftpReceiver = ftpPortClient.downloadFile(tmpDownFileName, tmpLocalMarkPath);
                ftpPortClient.disconnect();
            }

            if (ftpReceiver.isCompleted) {
                String tmpStrRet = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
                WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    retAts.respCode = "0";
                    retAts.reqSeqID = p_reqQryBat.reqBatchNO;

                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);
                    tmpReader.readLine();

                    while (true) {
                        String eachline = tmpReader.readLine();
                        if (StringHelper.isNullOrEmpty(eachline)) {
                            break;
                        }
                        if (eachline.indexOf("|") > 0) {
                            String[] bodyValues = eachline.split("\\|");
                            if (p_reqQryBat.reqBatchNO.equalsIgnoreCase(bodyValues[6].split("-")[0])) {
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

                                if (p_reqQryBat.reqHeader.transType.equals("1998")) {
                                    tmpRetDetail.recAct = bodyValues[1];
                                    tmpRetDetail.recName = bodyValues[4];
                                } else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
                                    tmpRetDetail.payAct = bodyValues[1];
                                    tmpRetDetail.payName = bodyValues[4];
                                }

                                tmpRetDetail.postScript = bodyValues[6].split("-")[1];
                                tmpRetDetail.payAmount = bodyValues[2];
                                tmpRetDetail.result = bodyValues[5];
                                tmpRetDetail.payInfoCode = bodyValues[5];

                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "银行返回明细数据格式非法!";
                        }
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "本地批次结果文件内容为空!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "批次结果文件下载失败:" + ftpReceiver.connMsg;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeAfterDetail();
        return retAts;
    }
}